package cn.sc.summer.security.listener;

import cn.sc.summer.token.po.UserDetailX;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.authentication.event.LogoutSuccessEvent;
import org.springframework.stereotype.Component;

/**
 * 登录监听器
 */
@Slf4j
@Component
public class LoginAuditListener {

    /**
     * 处理登录成功事件
     *
     * @param event 登录成功事件
     */
    @EventListener(AuthenticationSuccessEvent.class)
    public void onAuthenticationSuccessEvent(AuthenticationSuccessEvent event) {
        if (event.getAuthentication().getPrincipal() instanceof UserDetailX) {
            UserDetailX userDetailX = (UserDetailX) event.getAuthentication().getPrincipal();
            log.info("user: {}[{}] - login success!", userDetailX.getUsername(), userDetailX.getPhone());
        }
    }

    /**
     * 登录失败监听器
     *
     * @param event 事件
     */
    @EventListener(AbstractAuthenticationFailureEvent.class)
    public void onLogoutSuccessEvent(AbstractAuthenticationFailureEvent event) {
        log.warn("user: {} - login failure, reason: {}!", event.getAuthentication().getName(), event.getException().getMessage());
    }

    /**
     * 登出成功事件监听
     *
     * @param event 事件
     */
    @EventListener(LogoutSuccessEvent.class)
    public void onLogoutSuccessEvent(LogoutSuccessEvent event) {
        log.info("user: {} - logout success!", event.getAuthentication().getName());
    }

}
